import {
  getUserProfile,
  updateProfile,
  updatePhoto,
} from '@/store/actions/profile'
import { logout } from '@/store/actions/login'
import dayjs from 'dayjs'
// import { RootState } from '@/types/store'
import {
  Button,
  List,
  DatePicker,
  NavBar,
  Toast,
  Popup,
  Dialog,
} from 'antd-mobile'
import classNames from 'classnames'
// import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { useInitialState } from '@/utils/use-initial-state'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import styles from './index.module.scss'
import { useRef, useState } from 'react'
import { useHistory } from 'react-router-dom'

const Item = List.Item
type InputPoput = {
  type: '' | 'name' | 'intro'
  value: string
  visible: boolean
}
type ListPopup = {
  type: '' | 'gender' | 'photo'
  visible: boolean
}
const ProfileEdit = () => {
  const dispatch = useDispatch()
  const fileRef = useRef<HTMLInputElement>(null)

  const { userProfile } = useInitialState(getUserProfile, 'profile')
  const { birthday, gender, name, photo, intro } = userProfile
  // 控制修改昵称弹出层的显示或隐藏
  const [inputVisible, setInputVisible] = useState<InputPoput>({
    type: '',
    value: '',
    visible: false,
  })
  // 控制头像或性别弹出层的展示或隐藏
  const [listPopup, setListPopup] = useState<ListPopup>({
    type: '',
    visible: false,
  })
  //日期的
  const [showBirthday, setShowBirthday] = useState(false)
  //开启日期
  const onBirthdayShow = () => {
    setShowBirthday(true)
  }
  //关闭日期
  const onBirthdayHide = () => {
    setShowBirthday(false)
  }
  //开启性别的
  const onGenderShow = () => {
    setListPopup({
      type: 'gender',
      visible: true,
    })
  }
  //关闭性别的
  const onGenderHide = () => {
    setListPopup({
      type: '',
      visible: false,
    })
  }
  const history = useHistory()
  //更新用户信息
  const onUpdateProfile = async (
    type: 'name' | 'intro' | 'gender' | 'photo' | 'birthday',
    value: string
  ) => {
    if (type === 'photo') {
      fileRef.current?.click()
    } else {
      await dispatch(updateProfile({ [type]: value }))
      Toast.show({
        content: '更新成功',
        duration: 1000,
      })
    }

    onInputNo()
    onGenderHide()
  }
  const onPhotoShow = () => {
    setListPopup({
      type: 'photo',
      visible: true,
    })
  }
  // 开启
  const onInput = (type: InputPoput['type'], value: InputPoput['value']) => {
    setInputVisible({
      type,
      value,
      visible: true,
    })
  }
  //关闭
  const onInputNo = () => {
    setInputVisible({ type: '', value: '', visible: false })
  }
  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    const photoData = new FormData()
    photoData.append('photo', file)
    await dispatch(updatePhoto(photoData))
    onGenderHide()
    Toast.show({
      content: '上传成功',
      duration: 600,
    })
  }
  //改生日的
  const onUpdateBirthday = (value: Date) => {
    const birthday = dayjs(value).format('YYYY-MM-DD')

    onUpdateProfile('birthday', birthday)
    onBirthdayHide()
  }
  //退出功能
  const onLogout = () => {
    const handler = Dialog.show({
      title: '温馨提示',
      content: '亲，你确定退出吗？',
      // 表示：再点击 actions 对应按钮时关闭
      closeOnAction: true,
      // 表示：点击遮罩层关闭
      closeOnMaskClick: true,
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',

            onClick: () => {
              handler.close()
            },
          },
          {
            key: 'confirm',
            text: '退出',
            onClick: async () => {
              await dispatch(logout())
              history.push('/login')
            },
            style: {
              color: 'red',
            },
          },
        ],
      ],
    })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          onBack={() => history.go(-1)}
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={
                      photo || 'http://toutiao.itheima.net/images/user_head.jpg'
                    }
                    alt=""
                  />
                </span>
              }
              arrow
              onClick={onPhotoShow}
            >
              头像
            </Item>
            <Item arrow extra={name} onClick={() => onInput('name', name)}>
              昵称
            </Item>
            <Item
              arrow
              onClick={() => onInput('intro', intro ?? '')}
              extra={
                <span className={classNames('intro', 'normal')}>
                  {intro || '未填写'}
                </span>
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={gender + '' === '0' ? '男' : '女'}
              onClick={onGenderShow}
            >
              性别
            </Item>
            <Item arrow extra={birthday} onClick={onBirthdayShow}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={showBirthday}
            value={new Date(birthday)}
            onCancel={onBirthdayHide}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
            onConfirm={onUpdateBirthday}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={onLogout}>
            退出登录
          </Button>
        </div>
      </div>
      <Popup visible={inputVisible.visible} position="right">
        <EditInput
          key={inputVisible.type}
          onClose={onInputNo}
          value={inputVisible.value}
          onUpdateProfile={onUpdateProfile}
          type={inputVisible.type}
        />
      </Popup>
      <Popup visible={listPopup.visible} onMaskClick={onGenderHide}>
        <EditList
          onClose={onGenderHide}
          type={listPopup.type}
          onUpdateProfile={onUpdateProfile}
        />
      </Popup>
    </div>
  )
}

export default ProfileEdit
